package br.com.pb.bymychef.persistencia.dao.impl;

import java.io.Serializable;
import java.util.List;

import javax.inject.Inject;
import javax.persistence.EntityManager;
import javax.persistence.Query;

import br.com.pb.bymychef.persistencia.dao.interfaces.DAO;

public abstract class DAOImpl<T, Id extends Serializable> implements DAO<T, Id>, Serializable{

    private static final long serialVersionUID = 1L;

    private final Class<T> classe;

    @Inject
    protected EntityManager em;

    public DAOImpl(Class<T> classe) {
	this.classe = classe;
	System.out.println("GenericDAO - Construtor");
    }

    public T insert(T obj) {
	try {
	    obj = em.merge(obj);
	    em.getTransaction().commit();
	} catch (Exception e) {
	    // TODO: handle exception
	    em.getTransaction().rollback();
	    throw e;
	}
	return obj;
    }

    public void remove(T obj) {
	try {
	    em.remove(obj);
	    em.getTransaction().commit();
	} catch (Exception e) {
	    // TODO: handle exception
	    em.getTransaction().rollback();
	    throw e;
	}
    }

    public void update(T obj) {
	try {
	    em.merge(obj);
	    em.getTransaction().commit();
	} catch (Exception e) {
	    // TODO: handle exception
	    em.getTransaction().rollback();
	    throw e;
	}
    }

    public T findById(Id pk) {
	return em.find(classe, pk);
    }

    @SuppressWarnings("unchecked")
    public List<T> listaTodos() {
	
	return em.createQuery("select o from " + classe.getSimpleName() + " o")
		.getResultList();
    
    }

    @SuppressWarnings("unchecked")
    public List<T> listar(String jpql) {

	Query query = null;
	query = em.createQuery(jpql);

	List<T> itens = query.getResultList();
	return itens;
    }

    @SuppressWarnings("unchecked")
    public List<T> select(String SQL) {
	Query query = null;
	query = em.createNativeQuery(SQL, classe);

	List<T> itens = query.getResultList();
	return itens;
    }

    // public List<T> listar(String jpql, Map<String, Object> parametros) {
    //
    // Query query = null;
    // query = em.createQuery(jpql);
    //
    // if (Objeto.notBlank(parametros)) {
    // for (String chave : parametros.keySet()) {
    // query = query.setParameter(chave, parametros.get(chave));
    // }
    // } else {
    // query = em.createQuery(jpql);
    // }
    //
    // List<T> itens = query.getResultList();
    // return itens;
    // }

}
